package com.fadadianqi.logistics.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.logistics.sell.model.InOut;
import com.fadadianqi.logistics.sell.service.InOutService;
import com.yeqiangwei.commons.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class InOutController {

    private static final String VIEW_LIST = "admin/in-out/list";

    private static final String COMMAND_NAME = "inOutForm";

    @RequestMapping(URIMappingUtils.INVENTORY_PREFIX + "/in-out/list")
    public String showList(HttpServletRequest request, ModelMap modelMap) throws Exception {
        List<InOut> list = null;
        Integer total = null;
        Pagination pagination = null;

        Map<String, Object> params = new HashMap<String, Object>();

        String s = ParamUtils.getString(request, "s", null);
        String e = ParamUtils.getString(request, "e", null);
        if (s != null && e != null) {
            pagination = new Pagination(request, 100);
            String start = s + " 00:00:00";
            String end = e + " 23:59:59";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(start);
            Date date2 = sdf.parse(end);
            list = inOutService.findBetween(date1, date2, pagination);
            params.put("s", s);
            params.put("e", e);
            total = inOutService.countBetween(date1, date2);
        } else {
            pagination = new Pagination(request, 15);
            list = inOutService.findAll(pagination);
            total = inOutService.countAll();
        }
        double inTotal = 0D;
        double outTotal = 0D;
        if (ValidatorHelper.isNotEmpty(list)) {
            for (InOut item : list) {
                if (item.getMoney().doubleValue() > 0) {
                    inTotal += item.getMoney().doubleValue();
                } else {
                    outTotal += item.getMoney().doubleValue();
                }
            }
        }
        modelMap.put("inTotal", inTotal);
        modelMap.put("outTotal", outTotal);
        pagination.setTotal(total);
        pagination.setElements(params);
        PaginationHelper.setAttribute(request, pagination);
        modelMap.put("list", list);
        long now = DateTimeUtils.getTimeInMillis();
        String fmt = DateTimeUtils.FMT_YYYY_MM_DD_HH_MM_SS;
        modelMap.put("addTime", DateTimeUtils.format(now, fmt));
        return VIEW_LIST;
    }

    @RequestMapping(value = "/ajax/in-out/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> ajaxSave(@ModelAttribute(COMMAND_NAME) InOutForm form,
                                           BindingResult result, SessionStatus status) throws Exception {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        Boolean succeed = Boolean.TRUE;
        if (ValidatorHelper.isEmpty(form.getMemo())) {
            succeed = Boolean.FALSE;
        } else if (ValidatorHelper.isEmpty(form.getMoney())) {
            succeed = Boolean.FALSE;
        } else {
            double money = Math.abs(form.getMoney());
            if (form.getType() == 0) { //支出
                form.setMoney(-money);
            } else { // 收入
                form.setMoney(money);
            }
            if (ValidatorHelper.isNotEmpty(form.getAddTimeStr())) {
                if (form.getAddTimeStr().length() == 10) {
                    String timeString = DateTimeUtils.format(new Date().getTime(), "HH:mm:ss");
                    form.setAddTimeStr(form.getAddTimeStr() + " " + timeString);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date addTime = sdf.parse(form.getAddTimeStr());
                form.setAddTime(addTime);
            }
            inOutService.create(form);
        }
        status.setComplete();
        AjaxResult rs = new AjaxResult(form, succeed, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @Autowired
    private InOutService inOutService;

    public static final class InOutForm extends InOut {

        /**
         *
         */
        private static final long serialVersionUID = 6663106592947680904L;

        private int type;
        private String addTimeStr;

        public String getAddTimeStr() {
            return addTimeStr;
        }

        public void setAddTimeStr(String addTimeStr) {
            this.addTimeStr = addTimeStr;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }
    }
}
